package com.yusys.jin.blog.serviceimpl;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpSession;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import com.yusys.jin.blog.configuration.MenuConfig;
import com.yusys.jin.blog.entity.MailCode;
import com.yusys.jin.blog.entity.commonEntity.District;
import com.yusys.jin.blog.entity.commonEntity.ServerArea;
import com.yusys.jin.blog.entity.commonEntity.ServerServer;
import com.yusys.jin.blog.ex.DatabaseException;
import com.yusys.jin.blog.ex.InsertException;
import com.yusys.jin.blog.ex.SendTooFastException;
import com.yusys.jin.blog.mapper.CommonInfoMapper;
import com.yusys.jin.blog.mapper.MailCodeMapper;
import com.yusys.jin.blog.service.ICommonService;
import com.yusys.jin.blog.util.VerifiedCode;

@Service
public class CommonServiceimpl implements ICommonService {
    @Autowired
    MailCodeMapper mapper;
    @Autowired
    JavaMailSender sender;
    @Autowired
    CommonInfoMapper commonMapper;
    @Autowired
    MenuConfig menu;
    char[] letters = VerifiedCode.getLetters();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取小菜单名称
     *
     * @return
     * @throws DocumentException
     */


    @Override
    public void getMailCode(String to, HttpSession session) throws SendTooFastException, InsertException {
        // 从session中取出sessionid
        System.err.println(to + ":" + session);
        String id = session.getId();
        // 通过id查找数据库
        MailCode data = findInfo(id);
        MailCode mailcode = new MailCode();

        if (data == null) { // 如果数据库中没记录
            // 执行发邮件步骤
            String code = sendEmail(to);
            session.setAttribute("mailcode", code);
            // 封装发送记录
            mailcode.setSessionid(id);
            mailcode.setEmail(to);
            mailcode.setMailcode(code);
            mailcode.setTime(sdf.format(new Date()));
            addInfo(mailcode);
        } else {
            // 如果数据库有数据
            Date time = null;
            try {
                time = sdf.parse(data.getTime());
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Date now = new Date();
            long miao = (now.getTime() - time.getTime()) / 1000;
            System.err.println("相差" + miao + "秒");
            if (miao <= 120) {
                throw new SendTooFastException(120 - miao + ""); // 距离上次发送没有超过两分钟
            } else {
                String code = sendEmail(to); // 则从新发送验证码 并更新数据库
                session.setAttribute("mailcode", code);
                mailcode.setEmail(to);
                mailcode.setTime(sdf.format(new Date()));
                mailcode.setMailcode(code);
                mailcode.setSessionid(id);
                System.err.println(mailcode);
                updateInfo(mailcode);
            }
        }

    }

    @Override
    /**
     * 获取大区信息
     */
    public List<ServerArea> getAreas() {

        return getServerAreas();
    }

    @Override
    /**
     * 获取服务器信息
     */
    public List<ServerServer> getServers(Integer areaId) {
        return getServerServsers(areaId);
    }

    @Override
    /**
     * 获取全国地区名称
     */
    public List<District> getDistrict(Integer parentId) {

        return findDistrict(parentId);
    }

    @Override
    public Map<Integer, String> getMenus(Integer id) {
        Map<Integer, String> map = menu.getMap().get(id);
        return map;
    }

    // *******************************************以下是私有方法*************************************************************
    private List<District> findDistrict(Integer ParentId) {
        return commonMapper.findAllDistric(ParentId);
    }

    private List<ServerArea> getServerAreas() {
        List<ServerArea> list = new ArrayList<ServerArea>();
        list = commonMapper.findAllArea();
        if (list.size() == 0) {
            throw new DatabaseException("查询失败，请联系管理员进行下一步处理");
        }
        return list;
    }

    private List<ServerServer> getServerServsers(Integer AreaId) {
        List<ServerServer> list = new ArrayList<ServerServer>();
        list = commonMapper.findAllServer(AreaId);
        if (list.size() == 0) {
            throw new DatabaseException("查询失败，请联系管理员进行下一步处理");
        }
        return list;
    }

    private void updateInfo(MailCode code) {
        Integer rows = mapper.update(code);
        if (rows != 1) {
            throw new InsertException("插入邮件验证码失败，请联系管理员处理");
        }

    }

    private String sendEmail(String to) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("验证码");
        message.setFrom("110680320@qq.com");
        message.setTo(to);
        String code = getCode();
        message.setText("验证码有效期2分钟请尽快操作：" + code);
        sender.send(message);
        return code;
    }

    private void addInfo(MailCode code) {
        Integer rows = mapper.insert(code);
        if (rows != 1) {
            throw new InsertException();
        }
    }

    private MailCode findInfo(String sessionid) {
        MailCode code = mapper.findSessionByid(sessionid);
        return code;
    }

    private void deleteInfo(String sessionid) {
        Integer rows = mapper.delete(sessionid);
        if (rows != 1) {
            throw new DatabaseException();
        }
    }

    private String getCode() {
        Random rand = new Random();
        StringBuilder builder = new StringBuilder();
        // 生成随机验证码
        for (int i = 0; i < 4; i++) {
            int num = rand.nextInt(62);
            builder.append(letters[num]);
        }
        String str = builder.toString().trim();
        return str;
    }
}
